<?php

namespace Admin;

use Zend\Session\Container;

/**
 * 业务相关
 */
class AdminModel extends \Business\BusinessBase
{
    /**
     * 列表功能
     *
     * @param array $params
     * @return array
     */
    public function getList($params)
    {
        $page = empty($params['page']) ? 1 : $params['page'];
        $count = empty($params['count']) ? 10 : $params['count'];
        $where = empty($params['where']) ? null : $params['where'];
        $order = empty($params['order']) ? null : $params['order'];
        $baseUrl = empty($params['baseUrl']) ? null : $params['baseUrl'];

        $AdminDAOModel = AdminDAOModel::getInstance();
        $totalArr = $AdminDAOModel->fetchAll(array(new \Zend\Db\Sql\Expression('count(0) as total')), $where, null, 1);
        $totalNum = $totalArr[0]['total']; //总数

        $paginator = new \Our\Paginator($page, $totalNum, $count, array('baseUrl' => $baseUrl, 'ext' => '/'));
        $result = $AdminDAOModel->fetchAll(null, $where, array('admin_id asc'), $count, ($page - 1) * $count);

        $listData = array();
        foreach ($result as $val) {
            $listData[] = $this->adapterAdmin($val);
        }

        return [$listData, $paginator];
    }

    /**
     * 适配列表页显示
     */
    public function adapterAdmin($admin)
    {
        $data = array();
        $data['admin_id'] = $admin['admin_id'];
        $data['admin_name'] = $admin['admin_name'];
        $data['admin_email'] = $admin['admin_email'];
        $data['admin_mobile'] = $admin['admin_mobile'];
        $data['status_name'] = $admin['status'] == "1" ? "正常" : "禁用";
        $data['last_login_time'] = $admin['last_login_time'];
        $data['last_login_ip'] = $admin['last_login_ip'];
        return $data;
    }

    /**
     * 增加数据
     *
     * @param array $params
     *  content_title
     *  content
     *  content_image
     *  status
     * @return false|int
     */
    public function add($params)
    {
        $AdminDAOModel = AdminDAOModel::getInstance();
        $admin = $AdminDAOModel->findAdminByEmail($params['admin_email']);
        if ($admin) {
            \Error\ErrorModel::throwException(11010);
        }

        $params['admin_password'] = $this->encryptPassword($params['admin_password']);
        $params['add_time'] = time();
        $result = $AdminDAOModel->insert($params);
        if (!$result) {
            \Error\ErrorModel::throwException(10010);
        }

        return $result;
    }

    /**
     * 加密密码
     *
     * @param string $password
     * @return string
     */
    public function encryptPassword($password)
    {
        return md5($password);
    }

    /**
     * 管理员编辑功能
     *
     * @param array $params
     *  admin_id
     *  admin_name
     *  admin_email
     *  admin_password
     *  status
     * @return int
     * @throws \Exception
     */
    public function edit($params)
    {
        $AdminDAOModel = AdminDAOModel::getInstance();
        $admin = $AdminDAOModel->find($params['admin_id']);
        if (!$admin) {
            \Error\ErrorModel::throwException(11011);
        }

        $data = array(
            "admin_name" => $params['admin_name'],
            "status" => $params['status'],
        );
        // 如果有传入密码参数,则修改密码
        if ($params['admin_password']) {
            $data['admin_password'] = $this->encryptPassword($params['admin_password']);
        }
        // 检测是否有需要修改的数据
        if (!array_diff_assoc($data, $admin)) {
            return true;
        }

        $AdminDAOModel->beginTransaction();
        $result = $AdminDAOModel->update($data, array("admin_id" => $params['admin_id']));
        if (!$result) {
            $AdminDAOModel->rollback();
            \Error\ErrorModel::throwException(10010);
        }
        $AdminDAOModel->commit();
        return $result;
    }

    /**
     * 删除功能
     *
     * @param $params
     * @return bool
     */
    public function delete($params)
    {
        $ContentDAOModel = ContentDAOModel::getInstance();

        $ContentDAOModel->beginTransaction();
        $result = $ContentDAOModel->update(array('status' => 3), array('content_id' => $params['content_id']));
        if (!$result) {
            $ContentDAOModel->rollback();
            return false;
        }
        $ContentDAOModel->commit();
        return true;
    }

    /**
     * 处理内容
     *
     * @param string $content
     * @return string
     */
    protected function _formatContent($content)
    {
        $content = str_replace(array('&nbsp;', '　'), '', $content);
        $content = str_replace(array('<br />', '<br>'), '<br/>', $content);

        $array = explode('<br/>', $content);
        $array = \Our\Common::arrayTrim($array);

        $string = implode('<br />', $array);

        return $string;
    }

    //登录地址
    public static $_loginUrl = '/admin/login/index/';

    /**
     * 用户登录
     *
     * @param string $adminEmail
     * @param string $password
     * @return array
     */
    public function login($adminEmail, $password)
    {
        $AdminDAOModel = AdminDAOModel::getInstance();
        $admin = $AdminDAOModel->findAdminByEmail($adminEmail);
        if (!$admin) {
            \Error\ErrorModel::throwException(11011);
        }
        if ($admin['status'] != "1") {
            \Error\ErrorModel::throwException(11012);
        }
        if ($admin['admin_password'] != $this->encryptPassword($password)) {
            \Error\ErrorModel::throwException(11013);
        }

        $loginIp = \Our\Common::getClientIp();
        $loginTime = time();
        //更新登录记录
        $data = array('last_login_time' => $loginTime, 'last_login_ip' => $loginIp);
        $AdminDAOModel->update($data, array('admin_id=?' => $admin['admin_id']));

        //保存session
        $container = new \Zend\Session\Container('admin');
        $container->admin = $admin;

        return $admin;
    }

    /**
     * 检测管理员是否登录
     *
     * @return boolean|array 没有登录返回false，否则返回会员信息
     */
    public function validateLogin()
    {
        $container = new Container('admin');
        $admin = $container->admin;
        if (!$admin) {
            return false;
        }
        return $admin;
    }

    /**
     * 检测管理员状态
     *
     * @param int $adminId
     * @return boolean
     */
    public function checkStatus($adminId)
    {
        $AdminDAOModel = AdminDAOModel::getInstance();
        $result = $AdminDAOModel->find($adminId);
        if (!$result) {
            return true;
        }
        if ($result["status"] == "1") {
            return true;
        }
        return false;
    }

    /**
     * 登出
     */
    public function logout()
    {
        $container = new \Zend\Session\Container('admin');
        $container->admin = NULL;
    }

    /**
     * 计算用户登录的sso信息
     */
    public function calcSso($adminId)
    {
        $key = \Yaf\Registry::get('config')->get('auth_key');
        $sso = rawurlencode(\Our\Common::authcode($adminId, "ENCODE", $key));

        return $sso;
    }

    /**
     * 解密用户登录的sso信息
     */
    public function decodeSso($sso)
    {
        $key = \Yaf\Registry::get('config')->get('auth_key');
        $result = \Our\Common::authcode(rawurldecode($sso), "DECODE", $key);

        return $result;
    }

    /**
     * 适配列表页显示
     */
    public function adapterLog($log)
    {
        $data = array();
        $adminModel = \Dao\Admin\AdminModel::getInstance();
        $adminInfo = $adminModel->find($log['admin_id']);
        $data['admin_id'] = $log['admin_id'];
        $data['admin_name'] = empty($adminInfo['admin_name']) ? "" : $adminInfo['admin_name'];
        $data['log_info'] = $log['log_info'];
        $data['request_uri'] = $log['request_uri'];
        $data['request_params'] = $log['request_params'];
        $data['request_ip'] = $log['request_ip'];
        $data['add_time'] = date('Y-m-d H:i:s', $log['add_time']);
        return $data;
    }

    /**
     * 校验管理员
     *
     * @param int $adminId
     * @return array
     * @throws \Exception
     */
    public function getAdminById($adminId)
    {
        return $this->_validateAdmin($adminId);
    }

    /**
     * 校验管理员
     *
     * @param int $adminId
     * @return array
     * @throws \Exception
     */
    public function _validateAdmin($adminId)
    {
        $DAO = \DAO\Admin\AdminModel::getInstance();
        $admin = $DAO->find($adminId);
        if (!$admin) {
            \Error\ErrorModel::throwException(300006);
        }
        return $admin;
    }

    /**
     * 创建新密码
     *
     * @param int $length
     * @return string
     */
    protected function _createNewPwd($length = 12)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
        $password = '';
        for ($i = 0; $i < $length; $i++) {
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $password;
    }

    /**
     * 类实例
     *
     * @var \Admin\AdminModel
     */
    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \Admin\AdminModel
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}
